export const getUrlParam = (name, path) => {
  const u = path || window.location.search,
    reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)'),
    r = u.substr(u.indexOf('?') + 1).match(reg);
  const val = r != null ? r[2] : '';

  if (!val && !path && location.hash) return getUrlParam(name, location.hash);
  return r != null ? r[2] : '';
};

export const getTopLevelDomain = (all = '') => {
  let url = window.location.href;
  if (import.meta.env.MODE === 'development') {
    url = 'https://www.puzzle-game.pro';
  }
  url = url.replace('www.', '');
  let hostname = new URL(url).hostname;
  let parts = hostname.split('.');
  if (parts.length > 2 && all !== 'all') {
    return parts.slice(-2).join('.');
  } else {
    return hostname;
  }
};

export const getIcon = (game) => {
  if (game.local) {
    return game.icon;
  } else {
    return `//game.${getTopLevelDomain()}${game.icon}`;
  }
};

export const capitalizeFirstLetter = (str = '') => {
  return `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
};
export const toQuery = (obj) => {
  if (Object(obj) !== obj) return '';
  return Object.entries(obj)
    .map(([k, v]) => `${k}=${v}`)
    .join('&');
};
// ----------------------------------------------------------------
export const recently = {
  KEY: '_recently',
  get() {
    return JSON.parse(localStorage.getItem(recently.KEY) || '[]');
  },
  set(item) {
    const array = [item].concat(JSON.parse(localStorage.getItem(recently.KEY) || '[]'));
    const nLs = [];
    const arr = array.reduce((ls, item) => {
      if (!nLs.includes(item.name)) {
        nLs.push(item.name);
        const { name, icon, url } = item;
        ls.push({ name, icon, url });
      }
      return ls;
    }, []);
    localStorage.setItem(recently.KEY, JSON.stringify(arr));
  },
};

export const bodyScroll = {
  cssK: 'van-overflow-hidden',
  hide() {
    document.body.classList.add(bodyScroll.cssK);
  },
  recovery() {
    document.body.classList.remove(bodyScroll.cssK);
  },
};
export const categoryList = [
  'Recommend',
  'Sports',
  'Puzzle',
  'Classics',
  'Casual',
  'Strategy',
  'Shooting',
  'Kids',
  'Action',
  'Girls',
  'Adventure',
];

export const formatConfig = (obj) => {
  const { s, s2, p_slot, id, id2, p_id } = obj;
  return {
    ...obj,
    s: s || id,
    s2: s2 || id2,
    p_slot: p_slot || p_id,
  };
};

export const getQuery = (path = '') => {
  let url = path.toLowerCase();
  if (url.charAt(0) !== '/') url = '/' + url;
  const query = JSON.parse(
    JSON.stringify({ [getUrlParam('portal') ? 'portal' : 'channel']: window._portal || undefined }),
  );
  return { path: url, query };
};
